import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../api_client.dart';
import '../tools.dart';
import 'UserCacheManager.dart';
import 'birthday_selector.dart';
import 'gender_selector.dart';
import 'package:http/http.dart' as http;

class ProfileEditPage extends StatefulWidget {
  const ProfileEditPage({super.key});

  @override
  _ProfileEditPageState createState() => _ProfileEditPageState();
}

class _ProfileEditPageState extends State<ProfileEditPage> {
  final _formKey = GlobalKey<FormState>();

  String _name = '';
  String _phone = '';
  DateTime? _birthday;
  String _gender = '男';
  String _caseHistory = '';
  File? _image;
  String _openImage = '';

  final ImagePicker _picker = ImagePicker();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      initAsync();
    });
  }

  void initAsync() async {
    await getUserInfo();
  }

  void _showLoadingDialog() async {
    // 使用Future.delayed确保不在构建过程中调用Navigator
    Future.delayed(Duration.zero, () {
      if (mounted) { // 检查当前的State是否还挂载着
        showDialog(
            context: context,
            barrierDismissible: false,
            builder: (BuildContext context) {
              return const Center(child: CircularProgressIndicator());
            }
        );
      }
    });
  }

  Future<void> _userPro() async {
    // 使用路由名称将用户重定向到消息页面
    if (mounted) {
      Navigator.of(context).pushReplacementNamed(
        '/main',
        arguments: 3, // 指定激活的底部导航索引
      );
    }
  }

  void _hideLoadingDialog() {
    // 关闭加载动画
    Navigator.of(context, rootNavigator: true).pop();
  }

  Future<bool> getUserInfo() async {
    _showLoadingDialog();
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    _openImage = prefs.getString('avatarURL') ?? 'http://image.aiyuye.shop/AvatarURL/ic_launcher.png';
    try {
      final response = await ApiClient.sendGetRequest('user/findUserInfo');
      if (response != null) {
        final jsonMap = json.decode(response);
        if (jsonMap['success']) {
          final data = jsonMap['data'];
          _name = data['username'];
          _phone = data['phone'];
          _birthday = data['age'] != null ? DateFormat("yyyy-MM-dd").parse(data['age']) : null;
          _gender = data['sex'];
          _caseHistory = data['medicalRecord'] ?? '';
          _hideLoadingDialog();
          return true;
        }
      }
      SnackbarHelper.showToast("服务器错误，请联系管理员~！");
    } catch (e) {
      if (kDebugMode) {
        print(e);
      }
      SnackbarHelper.showToast("服务器错误，请联系管理员~！");
    }
    _hideLoadingDialog();
    return false;
  }

  Future<void> _pickImage() async {
    final XFile? pickedFile = await _picker.pickImage(source: ImageSource.gallery);
    if (pickedFile != null) {
      File file = File(pickedFile.path); // 创建 File 对象
      XFile? compressImage = await _compressImage(file); // 压缩图像

      if (compressImage != null) {
        _showLoadingDialog(); // 显示加载动画
        await _uploadImage(compressImage); // 执行图像上传
        _hideLoadingDialog(); // 隐藏加载动画

        // 上传完成后，更新UI状态
        setState(() {
          _image = File(compressImage.path); // 只在这里使用 setState
        });
      }
    }
  }

  void _handleBackButtonPressed() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('提示'),
        content: const Text('确定要返回吗？未保存的更改将会丢失。'),
        actions: <Widget>[
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop(); // 关闭对话框
              _userPro();
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  Future<void> _submitProfile() async {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();
      if (await _postProfile(_name, _phone, _birthday.toString(), _gender, _caseHistory)) {
        _showPostProfileLog();
      }
    }
  }

  void _showPostProfileLog() {
    _hideLoadingDialog(); // 隐藏加载动画
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('提交成功'),
        content: Text('姓名: $_name\n电话: $_phone\n年龄: $_birthday\n性别: $_gender\n病例: $_caseHistory'),
        actions: <Widget>[
          TextButton(
            onPressed: () {
              Navigator.of(context).pop(); // 首先关闭对话框
              _userPro();
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 压缩图片
  /// 参数：
  ///     file 图片文件
  /// _compressImage(file)
  Future<XFile?> _compressImage(File file) async {
    final tempDir = await getTemporaryDirectory();
    final tempPath = tempDir.path;
    final result = await FlutterImageCompress.compressAndGetFile(
      file.absolute.path,
      '$tempPath/img_${DateTime.now().millisecondsSinceEpoch}.jpg',
      quality: 80,
    );
    return result;
  }

  /// 上传图片到服务器
  /// 参数：
  ///     XFile 图片文件
  /// _uploadImage(image)
  Future<void> _uploadImage(XFile image) async {
    final prefs = await SharedPreferences.getInstance();
    final String? token = prefs.getString('userToken');
    Uri uri = Uri.parse("http://api.aiyuye.shop/user/AvatarImage");
    var request = http.MultipartRequest('POST', uri)
      ..files.add(await http.MultipartFile.fromPath('file', image.path))
      ..headers.addAll({
        'token': token.toString()
      });
    try {
      var response = await request.send();
      final responseBody = await response.stream.bytesToString();
      if (response.statusCode == 200) {
        Map<String, dynamic> jsonMap = jsonDecode(responseBody);
        bool success = jsonMap['success'];
        if (success) {
          final data = jsonMap['msg'];
          if (data != null) {
            _editUserAvatarURL(data);
            final avatarPath = await UserCacheManager.cacheAvatar(data);
            await UserCacheManager.saveUserInfo(
              avatarURL: data,
            );
            if (kDebugMode) {
              print('Avatar is cached at: $avatarPath');
            }
          } else {
            if (kDebugMode) {
              print('No avatar URL provided');
            }
          }
          if (kDebugMode) {
            print("头像上传成功");
            print(responseBody);
          }
        } else {
          _showSignInFalseDebugLog('头像上传', '失败');
          if (kDebugMode) {
            print("头像上传失败");
            print(responseBody);
          }
          return;
        }
      } else {
        _showSignInFalseDebugLog('头像上传', '失败');
        if (kDebugMode) {
          print("头像上传失败");
          print(responseBody);
        }
        return;
      }
    } catch (error) {
      _showSignInFalseDebugLog('头像上传', '失败 $error');
      if (kDebugMode) {
        print("头像上传失败");
        print('Error: $error');
        return;
      }
    }
    return;
  }

  /// 返回 URL 上传到数据库
  /// 参数：
  ///     URL 图片网络地址
  /// _editUserAvatarURL(url)
  Future<String?> _editUserAvatarURL(String url) async {
    final prefs = await SharedPreferences.getInstance();
    final String? token = prefs.getString('userToken');
    var headers = {
      'token': token.toString(),
      'Content-Type': 'application/x-www-form-urlencoded'
    };
    var request = http.Request('POST', Uri.parse('http://api.aiyuye.shop/user/editUserAvatarURL'));
    request.bodyFields = {
      'url': url
    };
    request.headers.addAll(headers);

    http.StreamedResponse response = await request.send();

    if (response.statusCode == 200) {
      final responseBody = await response.stream.bytesToString();
      if (kDebugMode) {
        print(responseBody);
      }
      return responseBody;
    } else {
      if (kDebugMode) {
        print(response.reasonPhrase);
      }
    }
    return null;
  }

  /// 信息弹窗
  /// 参数：
  ///     state 标题
  ///     message 消息
  /// _showSignInFalseDebugLog(state，message)
  void _showSignInFalseDebugLog(String state, String message) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(state),
          content: Text(message),
          actions: <Widget>[
            TextButton(
              child: const Text('确定'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  Future<bool> _postProfile(String username, String phone, String birthday, String gender, String caseHistory) async {
    _showLoadingDialog(); // 显示加载动画
    try {
      final prefs = await SharedPreferences.getInstance();
      final String? token = prefs.getString('userToken');
      var headers = {
        'token': token.toString(),
        'Content-Type': 'application/json'
      };

      final formData = {
        "username": username,
        "medicalRecord": caseHistory,
        "phone": phone,
        "sex": gender,
        "age": birthday
      };
      print(formData);
      var request = http.Request('POST', Uri.parse('http://api.aiyuye.shop/user/editUser'));
      request.body = jsonEncode(formData);
      request.headers.addAll(headers);
      http.StreamedResponse response = await request.send();

      if (response.statusCode == 200) {
        final responseBody = await response.stream.bytesToString();
        final jsonMap = json.decode(responseBody);
        if (jsonMap['success']) {
          return true;
        } else {
          final msg = jsonMap['msg'];
          _showSignInFalseDebugLog('信息', msg);
          if (kDebugMode) {
            print(jsonMap);
          }
          return false;
        }
      } else {
        if (kDebugMode) {
          print(response.reasonPhrase);
        }
      }
    } catch (e) {
      _showSignInFalseDebugLog('信息', e.toString());
      if (kDebugMode) {
        print(e);
      }
    }
    _hideLoadingDialog(); // 隐藏加载动画
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('编辑个人资料'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: _handleBackButtonPressed,
        ),
      ),
      body: FutureBuilder<bool>(
        future: getUserInfo(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          } else if (snapshot.hasError || !snapshot.hasData || !snapshot.data!) {
            return const Center(child: Text('无法加载用户数据，请尝试重新加载页面。'));
          }
          return Form(
            key: _formKey,
            child: ListView(
              padding: const EdgeInsets.all(16.0),
              children: <Widget>[
                if (_image != null)
                  CircleAvatar(
                    radius: 60,
                    backgroundImage: FileImage(_image!),
                    backgroundColor: Colors.transparent,
                  )
                else
                  CircleAvatar(
                    radius: 60,
                    backgroundColor: Colors.transparent,
                    child: CircleAvatar(
                      radius: 50,
                      backgroundImage: NetworkImage(_openImage),
                    ),
                  ),
                TextButton(
                  onPressed: _pickImage,
                  child: const Text('更改头像'),
                ),
                TextFormField(
                  initialValue: _name,
                  decoration: const InputDecoration(
                    labelText: '姓名',
                    hintText: '输入你的姓名',
                    icon: Icon(Icons.person),
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '请填写姓名';
                    }
                    return null;
                  },
                  onSaved: (value) => _name = value!,
                ),
                TextFormField(
                  initialValue: _phone,
                  decoration: const InputDecoration(
                    labelText: '电话',
                    hintText: '输入你的电话号码',
                    icon: Icon(Icons.phone),
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '请填写电话号码';
                    }
                    return null;
                  },
                  onSaved: (value) => _phone = value!,
                ),
                BirthdaySelector(
                  initialBirthday: _birthday,
                  onDateChanged: (newDate) {
                    _birthday = newDate;
                  },
                ),
                GenderSelector(
                  initialGender: _gender,
                  onGenderChanged: (newGender) {
                    _gender = newGender;
                  },
                ),
                TextFormField(
                  initialValue: _caseHistory,
                  decoration: const InputDecoration(
                    labelText: '病例',
                    hintText: '描述你的病例历史 一个一行',
                    icon: Icon(Icons.history),
                  ),
                  maxLines: 3,
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '请填写病例历史';
                    }
                    return null;
                  },
                  onSaved: (value) => _caseHistory = value!,
                ),
                ElevatedButton(
                  onPressed: _submitProfile,
                  child: const Text('提交'),
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}
